<template>
  <div class="asset-detail">
    <!-- 欢迎页面 - 当没有ID参数时显示 -->
    <div v-if="!route.params.id" class="welcome-page">
      <!-- 快速访问区域 -->
      <div class="quick-access-section">
        <el-card class="access-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>快速查看资产</span>
              <el-tag type="info" size="small">输入ID或名称快速跳转到资产详情</el-tag>
            </div>
          </template>
          
          <div class="access-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="access-item">
                  <label>按ID查看：</label>
                  <el-input
                    v-model="accessId"
                    placeholder="请输入资产ID"
                    clearable
                    @keyup.enter="accessById"
                    @clear="clearAccess"
                  >
                    <template #append>
                      <el-button @click="accessById" :loading="accessing">
                        <el-icon><View /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </el-col>
              
              <el-col :span="8">
                <div class="access-item">
                  <label>按名称查看：</label>
                  <el-input
                    v-model="accessName"
                    placeholder="请输入资产名称"
                    clearable
                    @keyup.enter="accessByName"
                    @clear="clearAccess"
                  >
                    <template #append>
                      <el-button @click="accessByName" :loading="accessing">
                        <el-icon><View /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </el-col>
              
              <el-col :span="8">
                <div class="access-item">
                  <label>按编码查看：</label>
                  <el-input
                    v-model="accessCode"
                    placeholder="请输入资产编码"
                    clearable
                    @keyup.enter="accessByCode"
                    @clear="clearAccess"
                  >
                    <template #append>
                      <el-button @click="accessByCode" :loading="accessing">
                        <el-icon><View /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </el-col>
            </el-row>
            
            <!-- 访问结果 -->
            <div v-if="accessResults.length > 0" class="access-results">
              <h4>找到的资产：</h4>
              <el-table :data="accessResults" stripe style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="资产名称" />
                <el-table-column prop="code" label="编码" width="120" />
                <el-table-column prop="category" label="分类" width="100" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="viewAsset(scope.row)">
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <!-- 无结果提示 -->
            <div v-else-if="hasAccessed && accessResults.length === 0" class="no-results">
              <el-empty description="未找到相关资产" />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 资产详情页面 - 当有ID参数时显示 -->
    <el-card v-else class="detail-card" shadow="hover" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>资产详情</span>
          <div class="header-actions">
            <el-button link type="primary" @click="handleEdit">编辑</el-button>
            <el-button link @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="assetDetail" class="detail-content">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="资产ID">{{ assetDetail.id }}</el-descriptions-item>
              <el-descriptions-item label="资产名称">{{ assetDetail.name }}</el-descriptions-item>
              <el-descriptions-item label="资产编码">{{ assetDetail.code }}</el-descriptions-item>
              <el-descriptions-item label="资产分类">{{ assetDetail.category }}</el-descriptions-item>
              <el-descriptions-item label="资产状态">
                <el-tag :type="getStatusType(assetDetail.status)">
                  {{ assetDetail.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="资产价值">¥{{ assetDetail.value?.toLocaleString() }}</el-descriptions-item>
              <el-descriptions-item label="位置">{{ assetDetail.location }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
          
          <el-col :span="12">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="购买日期">{{ assetDetail.purchaseDate }}</el-descriptions-item>
              <el-descriptions-item label="供应商">{{ assetDetail.supplier }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ assetDetail.createTime }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ assetDetail.updateTime }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
        
        <div class="detail-section">
          <h3 class="section-title">详细信息</h3>
          <el-row :gutter="40">
            <el-col :span="12">
              <div class="info-item">
                <label>资产描述：</label>
                <div class="info-content">{{ assetDetail.description || '暂无描述' }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>备注信息：</label>
                <div class="info-content">{{ assetDetail.remark || '暂无备注' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 维护记录 -->
        <div class="detail-section">
          <h3 class="section-title">维护记录</h3>
          <el-table :data="maintenanceRecords" stripe style="width: 100%">
            <el-table-column prop="date" label="维护日期" width="120" />
            <el-table-column prop="type" label="维护类型" width="120" />
            <el-table-column prop="description" label="维护描述" />
            <el-table-column prop="cost" label="维护费用" width="120">
              <template #default="scope">
                ¥{{ scope.row.cost?.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" width="120" />
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { View, Document, Tools, Clock, Edit, List, Plus } from '@element-plus/icons-vue'
import { assetApi, maintenanceApi, categoryApi } from '@/api'
import { AssetStatusCodeToText } from '@/utils/status'

const router = useRouter()
const route = useRoute()

// 分类缓存
const categories = ref<any[]>([])

// 资产详情数据
const assetDetail = ref<any>(null)
const loading = ref(false)

// 访问相关变量
const accessId = ref('')
const accessName = ref('')
const accessCode = ref('')
const accessing = ref(false)
const accessResults = ref<any[]>([])
const hasAccessed = ref(false)

// 维护记录
const maintenanceRecords = ref<any[]>([])

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '正常': 'success',
    '维护中': 'warning',
    '报废': 'danger'
  }
  return statusMap[status] || 'info'
}

// 加载全部分类并缓存
const loadCategories = async () => {
  const list: any = await categoryApi.getAll()
  categories.value = list || []
}

// 根据分类 ID 获取名称
const getCategoryName = (id: number | null | undefined) => {
  if (!id) return ''
  const found = categories.value.find((c: any) => c.id === id)
  return found ? found.name : ''
}

// 获取资产详情
const getAssetDetail = async (id: number) => {
  loading.value = true
  try {
    const res: any = await assetApi.getDetail(id)
    assetDetail.value = {
      id: res.id,
      name: res.name,
      code: res.code,
      category: getCategoryName(res.categoryId) || res.categoryName || res.categoryId,
      status: AssetStatusCodeToText[res.status] || res.status,
      value: res.value,
      location: res.location,
      purchaseDate: res.purchaseDate,
      supplier: res.supplier || '',
      description: res.description,
      remark: res.remark,
      createTime: res.createdAt,
      updateTime: res.updatedAt
    }
    // 获取维护记录
    try {
      maintenanceRecords.value = await maintenanceApi.getByAssetId(id) as any[]
    } catch (err) {
      console.error("获取维护记录失败", err)
      maintenanceRecords.value = []
      ElMessage.warning("获取维护记录失败")
    }
  } catch (err) {
    console.error("获取资产详情失败", err)
    ElMessage.error("获取资产详情失败")
    router.push('/asset/list')
  } finally {
    loading.value = false
  }
}

// 编辑资产
const handleEdit = () => {
  router.push(`/asset/edit/${route.params.id}`)
}

// 返回
const handleBack = () => {
  router.back()
}

// 跳转到资产列表
const goToAssetList = () => {
  router.push('/asset/list')
}

// 跳转到添加资产
const goToAddAsset = () => {
  router.push('/asset/add')
}

// 按ID访问
const accessById = async () => {
  if (!accessId.value.trim()) {
    ElMessage.warning('请输入资产ID')
    return
  }
  
  accessing.value = true
  hasAccessed.value = true
  
  try {
    const id = parseInt(accessId.value.trim())
    if (!isNaN(id)) {
      try {
        const detail: any = await assetApi.getDetail(id)
        accessResults.value = [{
          id: detail.id,
          name: detail.name,
          code: detail.code,
          category: detail.categoryId,
          status: AssetStatusCodeToText[detail.status] || detail.status
        }]
      } catch {
        accessResults.value = []
      }
    }
  } catch (error) {
    ElMessage.error('访问失败，请重试')
  } finally {
    accessing.value = false
  }
}

// 按名称访问
const accessByName = async () => {
  const keyword = accessName.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入资产名称')
    return
  }

  accessing.value = true
  hasAccessed.value = true

  try {
    const res: any = await assetApi.getList({ name: keyword, page: 1, size: 20 })
    accessResults.value = (res.list || []).map((n: any) => ({
      id: n.id,
      name: n.name,
      code: n.code,
      category: n.categoryId,
      status: AssetStatusCodeToText[n.status] || n.status
    }))

    if (accessResults.value.length > 0) {
      ElMessage.success(`找到 ${accessResults.value.length} 个相关资产`)
    } else {
      ElMessage.warning('未找到相关资产')
    }
  } catch (error) {
    ElMessage.error('访问失败，请重试')
  } finally {
    accessing.value = false
  }
}

// 按编码访问
const accessByCode = async () => {
  const keyword = accessCode.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入资产编码')
    return
  }

  accessing.value = true
  hasAccessed.value = true

  try {
    const res: any = await assetApi.getList({ page: 1, size: 50 })
    const records = (res.list || []).filter((n: any) => (n.code || '').toUpperCase().includes(keyword.toUpperCase()))
    accessResults.value = records.map((n: any) => ({
      id: n.id,
      name: n.name,
      code: n.code,
      category: n.categoryId,
      status: AssetStatusCodeToText[n.status] || n.status
    }))

    if (accessResults.value.length > 0) {
      ElMessage.success(`找到 ${accessResults.value.length} 个相关资产`)
    } else {
      ElMessage.warning('未找到相关资产')
    }
  } catch (error) {
    ElMessage.error('访问失败，请重试')
  } finally {
    accessing.value = false
  }
}

// 清除访问结果
const clearAccess = () => {
  accessResults.value = []
  hasAccessed.value = false
}

// 查看资产
const viewAsset = (asset: any) => {
  if (!asset.id) {
    ElMessage.warning('无法获取资产ID')
    return
  }
  router.replace(`/asset/detail/${asset.id}`)
}

// 编辑资产
const editAsset = (asset: any) => {
  router.push(`/asset/edit/${asset.id}`)
}

onMounted(async () => {
  await loadCategories()
  const id = route.params.id as string
  if (id) {
    await getAssetDetail(parseInt(id))
  }
})

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    getAssetDetail(parseInt(newId as string))
  } else {
    assetDetail.value = null
  }
})
</script>

<style scoped>
.asset-detail {
  padding: 20px;
}

.welcome-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.quick-access-section {
  width: 100%;
  max-width: 800px;
}

.access-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.access-content {
  padding: 20px;
}

.access-item {
  margin-bottom: 20px;
}

.access-item label {
  font-weight: bold;
  color: #303133;
  display: block;
  margin-bottom: 5px;
}

.access-item .el-input {
  width: 100%;
}

.access-item .el-input .el-button {
  width: 100%;
}

.access-results {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.access-results h4 {
  margin-bottom: 10px;
  color: #303133;
  font-size: 16px;
  font-weight: bold;
}

.no-results {
  text-align: center;
  padding: 20px;
}

.recent-assets {
  margin-top: 20px;
}

.recent-card {
  max-width: 600px;
  width: 100%;
}

.recent-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-card .card-header .el-button {
  margin-left: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.detail-content {
  padding: 20px 0;
}

.detail-section {
  margin-top: 30px;
}

.section-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.info-item {
  margin-bottom: 15px;
}

.info-item label {
  font-weight: bold;
  color: #303133;
  display: block;
  margin-bottom: 5px;
}

.info-content {
  color: #606266;
  line-height: 1.6;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 60px;
}

@media (max-width: 768px) {
  .asset-detail {
    padding: 10px;
  }
  
  .welcome-actions {
    flex-direction: column;
  }
}
</style> 